package reflect.hibernate;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/28
 * 反射: “暴力破解”
 * 1.破坏封装性
 * 2.破坏泛型
 *
 * 需求：获取对象的所有属性及其值，以 name-张三 ，num-101 ， age=18存入obj.txt文件中
 * 格式如下：
----------Teacher+-----------
name - 王朝
workAge - 10
major - 舞蹈
----------Student+-----------
name - 张三
num - 101
age - 18
 */
public class HibernateDemo {
    public static void main(String[] args) {
        Student student = new Student("张三",101,18);
        Teacher teacher=new Teacher("王朝",10,"舞蹈");
        try {
            print(teacher);
            print(student);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void print(Object obj) throws InstantiationException, IllegalAccessException, IOException {
        //获得class对象
        Class<?> clazz = obj.getClass();//方法中形参类型是Object类型
        //创建目标文件对象
        File file=new File("obj.txt");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        // 创建文件写入流,可以追加
        PrintWriter pw=new PrintWriter(new FileWriter(file,true));
        //使用反射获取对象的所有属性
        Field[] fields = clazz.getDeclaredFields();
        pw.println("------------"+clazz.getSimpleName()+"-------------------");
        for (Field field : fields) {
            //破坏封装性，允许访问私有属性
            field.setAccessible(true);
            String fieldName = field.getName();
            Object object = field.get(obj);
            pw.println(fieldName + "-" + object);
        }
        System.out.println("打印成功!");
        pw.close();
    }
}
